package com.seio.edc.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.nova.edc.model.system.Menu;
import com.nova.edc.service.system.MenuService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.api.edc.model.ApiConstant;
import com.nova.edc.model.system.Login;
import com.nova.edc.service.system.LoginService;

/**
 * <p>
 * Project Name: EMS智能节能监测平台<br>
 * Description: SpringMVC 拦截器 <br>
 * File Name: ControllerInterceptor.java <br>
 * Copyright: Copyright (C) 2013 All Rights Reserved.
 */
@SuppressWarnings("unused")
public class ControllerInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private LoginService loginService;
	@Autowired
	private MenuService novaMenuService;

	private String path = "";
	private String basePath = "";

	/**
	 * 在Controller方法前进行拦截
	 */
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String queryString = request.getQueryString();
		if (queryString!=null&&queryString.contains("menuid=")) {
			String[] split = queryString.split("menuid=");
			int menuid = Integer.parseInt(split[1]);
			Menu menu = novaMenuService.getById(menuid);
			if (menu != null && menu.getParentid() > 0) {
				request.getSession().setAttribute("menuid", menu.getParentid());
			}else {
				request.getSession().setAttribute("menuid", 0);
			}
		}
		// 菜单权限控制
		String url = request.getRequestURI();
		if (url.indexOf("app") > 0) {
			Login login = (Login) request.getSession().getAttribute(
					ApiConstant.APP_SESSION_LOGIN);
			if (login != null || url.indexOf("appLogin") > 0 || url.indexOf("reportapp") > 0) {
				return true;
			} else {
				response.sendRedirect("/led2/appsessiontimeout.html");
				return false;
			}

		}
		int startindex = url.lastIndexOf("/");
		int endindex = url.lastIndexOf(".shtml");
		url = url.substring(startindex + 1, endindex);
		if ("index".equals(url) || "toEvery".equals(url)) {// 登录页面不用check
			return true;
		}

		// session是否过期判断
		String loginname = (String) request.getSession().getAttribute(
				"loginname");
		if (loginname == null || loginname.trim().length() == 0) {
//			String path = StringUtils.isEmpty(request.getContextPath()) ? "/"
//					: request.getContextPath();
			path = "/sessiontimeout.jsp";
			response.sendRedirect(path);
			return false;
		}

		// 根据用户类型是否有系统设置权限
		Login login = (Login) request.getSession().getAttribute("sessionLogin");
		if (login.getRoleid() == 1
				&& (request.getRequestURI().contains("systemMenu") || request
						.getRequestURI().contains("Password"))) { // 【0】系统管理员
																	// 【1】普通用户
			// 没权限访问的模块页面
			response.setHeader("Content-type", "text/html;charset=UTF-8");// 告知浏览器编码方式;
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			StringBuilder builder = new StringBuilder();
			builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
			builder.append("alert(\"没权限访问此页面！\");");
			builder.append("</script>");
			out.write(builder.toString());
			out.close();
			return false;
		}

		return true;
	}

	/**
	 * This implementation is empty.
	 */
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// System.out.println("ControllerInterceptor.postHandle()");
	}

	/**
	 * 在Controller方法后进行拦截
	 */
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// System.out.println("ControllerInterceptor.afterCompletion()");
	}

	// private HashMap<String, String> setPermissionMap() {
	// HashMap<String, String> permissionMap = new HashMap<String, String>();
	//
	// // 研究中心 url 权限设定。key：方法 value：【0】系统管理员 【1】CRC【2】CRA【3】DM【4】PM
	// permissionMap.put("yjzxglMain", "0");
	// permissionMap.put("yjzxglView", "0");
	// permissionMap.put("yjzxglAdd", "0");
	// permissionMap.put("yjzxglSave", "0");
	// permissionMap.put("yjzxglshowDetail", "0");
	// permissionMap.put("yjzxglCheckBH", "0");
	//
	// // 研究中心的操作用户管理 url 权限设定
	// permissionMap.put("yjzxglUserMain", "0");
	// permissionMap.put("yjzxglUserAdd", "0");
	// permissionMap.put("yjzxglUserAddProc", "0");
	// permissionMap.put("yjzxglCheckName", "0");
	// permissionMap.put("yjzxglUserShowDetail", "0");
	// permissionMap.put("yjzxglUserView", "0");
	// permissionMap.put("yjzxglUserSave", "0");
	// permissionMap.put("yjzxglUserRePassword", "0");
	//
	// // CRA用户管理 url 权限设定
	// permissionMap.put("craMain", "0,3,4"); // 查询页面admin,dm,pm
	// permissionMap.put("checkName", "0");
	// permissionMap.put("craShowDetail", "0,3,4");
	// permissionMap.put("craRePassword", "0");
	// permissionMap.put("craAdd", "0");
	// permissionMap.put("craSave", "0");
	// permissionMap.put("craView", "0,1,2,3,4");
	// permissionMap.put("craCheckName", "0");
	// permissionMap.put("addCraunit", "0");
	// permissionMap.put("afterSave", "0");
	// permissionMap.put("deleteCraunit", "0");
	//
	// // DM用户管理 url 权限设定
	// permissionMap.put("dmManagerMain", "0");
	// permissionMap.put("dmManagerView", "0");
	// permissionMap.put("dmManagerAdd", "0");
	// permissionMap.put("dmManagerInsert", "0");
	// permissionMap.put("dmManagerCheckRepeat", "0");
	// permissionMap.put("dmManagerShowDetail", "0");
	// permissionMap.put("dmManagerSave", "0");
	// permissionMap.put("dmManagerPasswordReset", "0");
	//
	// // PM用户管理 url 权限设定
	// permissionMap.put("pmManagerMain", "0");
	// permissionMap.put("pmManagerView", "0");
	// permissionMap.put("pmManagerAdd", "0");
	// permissionMap.put("pmManagerInsert", "0");
	// permissionMap.put("pmManagerCheckRepeat", "0");
	// permissionMap.put("pmManagerShowDetail", "0");
	// permissionMap.put("pmManagerSave", "0");
	// permissionMap.put("pmManagerPasswordReset", "0");
	//
	// // 第一阶段调查问卷管理 url 查询页面权限设定
	// permissionMap.put("firstphaseMain", "1");
	// permissionMap.put("firstphasecra", "2");
	// permissionMap.put("firstphasedm", "3");
	// permissionMap.put("firstphasepm", "4");
	// permissionMap.put("firstphaseMainshowDetail", "1,2,3,4");
	// permissionMap.put("crashowDetail1", "1,2,3,4");
	// permissionMap.put("dmshowDetail2", "1,2,3,4");
	// permissionMap.put("pmshowDetail3", "1,2,3,4");
	//
	// // 第一阶段调查开启 url 查询页面权限设定
	// permissionMap.put("firstphasestartMain", "0");
	// permissionMap.put("firstPhaseStartShowDetail", "0");
	// permissionMap.put("firstPhaseStart", "0");
	// // 第一阶段调查关闭 url 查询页面权限设定
	// permissionMap.put("firstphasecloseMain", "0");
	// permissionMap.put("firstPhaseCloseShowDetail", "0");
	// permissionMap.put("firstPhaseClose", "0");
	//
	// // 第二阶段调查问卷管理 url 查询页面权限设定
	// permissionMap.put("secondphaseMain", "1");
	// permissionMap.put("secondphasecra", "2");
	// permissionMap.put("secondphasedm", "3");
	// permissionMap.put("secondphasepm", "4");
	// permissionMap.put("secondphaseMainshowDetail", "1,2,3,4");
	// permissionMap.put("secondphasecrashowDetail", "1,2,3,4");
	// permissionMap.put("secondphasedmshowDetail", "1,2,3,4");
	// permissionMap.put("secondphasepmshowDetail", "1,2,3,4");
	//
	// // 第一阶段调查问卷管理 url 页面权限设定
	// permissionMap.put("getUnitStatus", "1,2,3,4");
	// permissionMap.put("fatSurveyAdd", "1,2,3,4");
	// permissionMap.put("fatSurveyView", "1,2,3,4");
	// permissionMap.put("fatSurveyUpdate", "1,2,3,4");
	// permissionMap.put("fatsurveyInsert", "1,2,3,4");
	// permissionMap.put("updateFatSurvey", "1,2,3,4");
	// permissionMap.put("deleteFatSurvey", "1,2,3,4");
	// permissionMap.put("askAnswerRecord", "1,2,3,4");
	// permissionMap.put("askAnswer_answer", "1,2,3,4");
	// permissionMap.put("askAnswer_question", "1,2,3,4");
	// permissionMap.put("askAnswer_close", "1,2,3,4");
	// permissionMap.put("oneAskAnswerRecord", "1,2,3,4");
	// permissionMap.put("updateRecord", "1,2,3,4");
	// permissionMap.put("searchUpdateRecord", "1,2,3,4");
	// permissionMap.put("generatorID", "1,2,3,4");
	//
	// // 第二阶段调查问卷管理 url 页面权限设定
	// permissionMap.put("healthsurveyquestionnaireNewInit", "1,2,3,4");
	// permissionMap.put("healthsurveyquestionnaireNew", "1,2,3,4");
	// permissionMap.put("healthsurveyquestionnaireUpdateInit", "1,2,3,4");
	// permissionMap.put("healthsurveyquestionnaireUpdate", "1,2,3,4");
	// permissionMap.put("healthsurveyquestionnaireDetail", "1,2,3,4");
	// permissionMap.put("healthsurveyquestionnaireDeleteInit", "1,2,3,4");
	// permissionMap.put("healthsurveyquestionnaireDelete", "1,2,3,4");
	// permissionMap.put("GozhiyiMain", "1,2,3,4");
	// permissionMap.put("Addzhiyi", "1,2,3,4");
	// permissionMap.put("Updatezhiyi", "1,2,3,4");
	// permissionMap.put("getparticipantID", "1,2,3,4");
	// permissionMap.put("zhiyiInit", "1,2,3,4");
	// permissionMap.put("getperZhiyiStatusmap", "1,2,3,4");
	//
	// // 第二阶段调查开启 url 查询页面权限设定
	// permissionMap.put("secondphasestartMain", "0");
	// permissionMap.put("secondPhaseStartShowDetail", "0");
	// permissionMap.put("secondPhaseStart", "0");
	// // 第二阶段调查关闭 url 查询页面权限设定
	// permissionMap.put("secondphasecloseMain", "0");
	// permissionMap.put("secondPhaseCloseShowDetail", "0");
	// permissionMap.put("secondPhaseClose", "0");
	//
	// // 密码重置 url 页面权限设定
	// permissionMap.put("passwordAlterMain", "0,1,2,3,4");
	// permissionMap.put("passwordAlter", "0,1,2,3,4");
	//
	// return permissionMap;
	// }

}
